<template>
  <div class="contracts-container">
    <div class="header">
      <h2>合同管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="success" @click="handleExportExcel" style="margin-left: 10px;">
           <el-icon><Download /></el-icon>
           <span>导出Excel</span>
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.employee_name"
        placeholder="搜索员工姓名"
        style="width: 200px"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-radio-group v-model="searchForm.status" @change="handleSearch">
        <el-radio label="active">未到期</el-radio>
        <el-radio label="expired">已到期</el-radio>
      </el-radio-group>
    </div>

    <div class="table-container">
      <el-table
        :data="tableData"
        style="min-width: 1200px; width: 100%;"
        v-loading="loading"
        :fit="true"
        size="small"
      >
        <el-table-column prop="employee_name" label="员工姓名" min-width="120" show-overflow-tooltip />
        <el-table-column prop="contract_number" label="合同编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="contract_type" label="合同类型" min-width="100">
          <template #default="scope">
            <el-tag
              :type="getContractTypeTag(scope.row.contract_type)"
            >
              {{ scope.row.contract_type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contract_party" label="合同主体" min-width="120" show-overflow-tooltip />
        <el-table-column prop="phone" label="联系电话" min-width="120" show-overflow-tooltip />
        <el-table-column prop="start_date" label="合同签订日期" min-width="120">
          <template #default="scope">
            {{ formatDate(scope.row.start_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_date" label="合同到期日期" min-width="120">
          <template #default="scope">
            {{ formatDate(scope.row.end_date) }}
          </template>
        </el-table-column>
        <el-table-column label="合同年限" min-width="100">
          <template #default="scope">
            {{ calculateContractYears(scope.row.start_date, scope.row.end_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="is_expired" label="合同状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_expired ? 'danger' : 'success'">
              {{ scope.row.is_expired ? '已到期' : '未到期' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          min-width="180"
          fixed="right"
          align="right"
        >
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="warning" @click="handleView(scope.row)">
                <el-icon><View /></el-icon>
                <span>查看</span>
              </el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑合同对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="80%"
      style="max-width: 1200px"
      :destroy-on-close="true"
      class="contract-dialog adaptive-dialog"
      top="5vh"
    >
      <div class="dialog-content adaptive-dialog-content">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
          :disabled="dialogType === 'view'"
      >
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="员工名称" prop="employee_id">
                <el-select
                  v-model="form.employee_id"
                  placeholder="请选择员工"
                  filterable
                  remote
                  :remote-method="remoteSearchEmployee"
                  :loading="employeeLoading"
                  style="width: 100%"
                  :disabled="dialogType === 'view'"
                >
                  <el-option
                    v-for="item in employeeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同编号" prop="contract_number">
                <el-input 
                  v-model="form.contract_number" 
                  placeholder="请输入合同编号"
                  :disabled="dialogType === 'view'"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同类型" prop="contract_type">
                <DictSelect
                  v-model="form.contract_type"
                  type="CONTRACT_TYPE"
                  placeholder="请选择合同类型"
                  style="width: 100%"
                  :disabled="dialogType === 'view'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同主体" prop="contract_party">
                <el-input 
                  v-model="form.contract_party" 
                  placeholder="请输入合同主体"
                  :disabled="dialogType === 'view'"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="签订日期" prop="start_date">
                <el-date-picker
                  v-model="form.start_date"
                  type="date"
                  placeholder="选择签订日期"
                  style="width: 100%"
                  :disabled="dialogType === 'view'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="到期日期" prop="end_date">
                <el-date-picker
                  v-model="form.end_date"
                  type="date"
                  placeholder="选择到期日期"
                  style="width: 100%"
                  :disabled="dialogType === 'view'"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        </el-form>
        <!-- 附件区块 -->
        <div class="attachment-section">
          <div class="attachment-card contract-attachment-card">
            <div class="contract-attachment-card-header">
              <!-- 删除右上角上传附件按钮，只保留弹窗入口 -->
            </div>
            <div class="contract-attachment-card-content">
            <attachment-list
              :attachments="contractAttachments"
              :loading="attachmentsLoading"
              :readonly="dialogType === 'view'"
              :download-function="downloadAttachment"
              :delete-function="deleteAttachment"
              :preview-function="previewAttachment"
              @refresh="loadContractAttachments"
              @add-attachment="showUploadDialog = true"
            />
          </div>
          </div>
        </div>
    <!-- 附件上传对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传附件"
      width="500px"
      @closed="handleUploadDialogClosed"
    >
      <AttachmentUploader
        module="contracts"
        :moduleId="currentId"
        @upload-success="handleUploadSuccess"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUploadDialog = false">关闭</el-button>
        </span>
          </template>
        </el-dialog>
      </div>
      <template #footer>
        <div class="dialog-footer" style="text-align:right;">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            v-if="dialogType !== 'view'"
            type="primary"
            @click="submitForm"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Download, View, Edit, Delete } from '@element-plus/icons-vue'
import { contractAPI, attachmentAPI, employeeAPI } from '../api'
import AttachmentList from '../components/AttachmentList.vue'
import AttachmentUploader from '../components/AttachmentUploader.vue'
import DictSelect from '../components/DictSelect.vue'

export default {
  name: 'Contracts',
  components: {
    Search,
    Plus,
    Download,
    View,
    Edit,
    Delete,
    AttachmentList,
    AttachmentUploader,
    DictSelect
  },
  setup() {
    // 表格数据
    const tableData = ref([])
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const tableHeight = ref('calc(100vh - 280px)')

    // 搜索表单
    const searchForm = ref({
      employee_name: '',
      status: 'active'  // 默认为未到期
    })

    // 新增/编辑表单
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const formRef = ref(null)
    const form = ref({
      id: null,
      employee_id: '',
      contract_number: '',
      contract_type: '',
      contract_party: '',
      start_date: '',
      end_date: ''
    })

    // 附件相关
    const currentId = ref(null)
    const contractAttachments = ref([])
    const attachmentsLoading = ref(false)
    const showUploadDialog = ref(false)

    // 员工选择相关
    const employeeOptions = ref([])
    const employeeLoading = ref(false)

    // 表单验证规则
    const rules = {
      contract_number: [
        { required: true, message: '请输入合同编号', trigger: 'blur' }
      ],
      contract_type: [
        { required: true, message: '请选择合同类型', trigger: 'change' }
      ],
      contract_party: [
        { required: true, message: '请输入合同主体', trigger: 'blur' }
      ],
      employee_id: [
        { required: true, message: '请选择员工', trigger: 'change' }
      ],
      start_date: [
        { required: true, message: '请选择合同签订日期', trigger: 'change' }
      ],
      end_date: [
        { required: true, message: '请选择合同到期日期', trigger: 'change' }
      ]
    }

    // 获取合同列表
    const getContractList = async () => {
      try {
        loading.value = true
        const response = await contractAPI.getAll(currentPage.value, pageSize.value, searchForm.value)
        let dataArr = []
        if (Array.isArray(response.data)) {
          dataArr = response.data
          total.value = response.data.length
        } else {
          dataArr = response.data.items || []
          total.value = response.data.total || 0
        }
        // 补全employee_name字段（如无则查员工信息）
        const promises = dataArr.map(async item => {
          if (!item.employee_name && item.employee_id) {
            try {
              const empRes = await employeeAPI.getById(item.employee_id)
              item.employee_name = empRes.data.name || ''
            } catch (e) {
              item.employee_name = ''
            }
          }
          return item
        })
        tableData.value = await Promise.all(promises)
      } catch (error) {
        ElMessage.error('获取合同列表失败')
        console.error('获取合同列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 远程搜索员工
    const remoteSearchEmployee = async (query) => {
      if (query) {
        employeeLoading.value = true
        try {
          const response = await contractAPI.searchEmployees(query)
          employeeOptions.value = response.data
        } catch (error) {
          console.error('搜索员工失败:', error)
        } finally {
          employeeLoading.value = false
        }
      } else {
        employeeOptions.value = []
      }
    }

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      getContractList()
    }

    // 获取合同类型对应的标签类型
    const getContractTypeTag = (type) => {
      if (type === '劳动合同') return 'success'
      const typeMap = {
        '劳务合同': 'warning',
        '实习协议': 'info'
      }
      return typeMap[type] || ''
    }

    // 处理新增
    const handleAdd = () => {
      dialogType.value = 'add'
      form.value = {
        id: null,
        employee_id: '',
        contract_number: '',
        contract_type: '',
        contract_party: '',
        start_date: '',
        end_date: ''
      }
      currentId.value = null
      dialogVisible.value = true
    }

    // 处理编辑
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      form.value = {
        id: row.id,
        employee_id: row.employee_id,
        contract_number: row.contract_number,
        contract_type: row.contract_type,
        contract_party: row.contract_party,
        start_date: row.start_date,
        end_date: row.end_date
      }
      currentId.value = row.id
      loadContractAttachments()
      // 初始化员工选项，保证下拉有当前员工
      if (row.employee_id && row.employee_name) {
        employeeOptions.value = [{ id: row.employee_id, name: row.employee_name }]
      } else {
        employeeOptions.value = []
      }
      dialogVisible.value = true
    }

    // 处理删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确定要删除该合同记录吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await contractAPI.delete(row.id)
          ElMessage.success('删除成功')
          getContractList()
        } catch (error) {
          ElMessage.error('删除失败')
          console.error('删除失败:', error)
        }
      }).catch(() => {})
    }

    // 处理查看
    const handleView = (row) => {
      dialogType.value = 'view'
      form.value = {
        id: row.id,
        employee_id: row.employee_id,
        contract_number: row.contract_number,
        contract_type: row.contract_type,
        contract_party: row.contract_party,
        start_date: row.start_date,
        end_date: row.end_date
      }
      currentId.value = row.id
      loadContractAttachments()
      // 初始化员工选项，保证下拉有当前员工
      if (row.employee_id && row.employee_name) {
        employeeOptions.value = [{ id: row.employee_id, name: row.employee_name }]
      } else {
        employeeOptions.value = []
      }
      dialogVisible.value = true
    }

    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogType.value === 'add') {
              const response = await contractAPI.create(form.value)
              ElMessage.success('新增成功')
              // 设置当前ID，以便可以管理附件
              currentId.value = response.data.id
              dialogType.value = 'edit'
            } else {
              await contractAPI.update(form.value.id, form.value)
              ElMessage.success('更新成功')
              dialogVisible.value = false
            }
            getContractList()
          } catch (error) {
            ElMessage.error(dialogType.value === 'add' ? '新增失败' : '更新失败')
            console.error('提交表单失败:', error)
          }
        }
      })
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      getContractList()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      getContractList()
    }

    // 表格大小调整处理
    const handleTableResize = () => {
      tableHeight.value = 'calc(100vh - 280px)'
    }

    // 日期格式化
    const formatDate = (date) => {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    // 计算合同年限
    const calculateContractYears = (startDate, endDate) => {
      if (!startDate || !endDate) return '-'
      const start = new Date(startDate)
      const end = new Date(endDate)
      
      // 将结束日期加1天，因为合同结束日期是前一天
      end.setDate(end.getDate() + 1)
      
      // 计算天数差
      const diffTime = Math.abs(end - start)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      // 转换为年
      const years = diffDays / 365
      
      // 如果是整数年，则不显示小数部分
      if (Math.abs(years - Math.round(years)) < 0.1) {
        return Math.round(years).toString()
      }
      
      // 否则保留一位小数
      return years.toFixed(1)
    }

    // 对话框标题计算属性
    const dialogTitle = computed(() => {
      const titleMap = {
        'add': '新增合同',
        'edit': '编辑合同',
        'view': '查看合同'
      }
      return titleMap[dialogType.value] || '合同信息'
    })

    // 附件相关功能
    // 加载合同附件
    const loadContractAttachments = async () => {
      if (!currentId.value) return
      
      attachmentsLoading.value = true
      try {
        const response = await contractAPI.getAttachments(currentId.value)
        contractAttachments.value = response.data
      } catch (error) {
        ElMessage.error('获取附件列表失败')
        console.error('获取附件列表失败:', error)
      } finally {
        attachmentsLoading.value = false
      }
    }
    
    // 上传合同附件
    const uploadContractAttachment = (contractId, file, description) => {
      return contractAPI.addAttachment(contractId, file, description)
    }
    
    // 处理上传成功
    const handleUploadSuccess = () => {
      ElMessage.success('附件上传成功')
      loadContractAttachments()
    }
    
    // 下载附件
    const downloadAttachment = (attachmentId) => {
      return attachmentAPI.download(attachmentId)
    }
    
    // 删除附件
    const deleteAttachment = (attachmentId) => {
      return contractAPI.deleteAttachment(currentId.value, attachmentId)
    }
    
    // 预览附件
    const previewAttachment = (attachmentId) => {
      return attachmentAPI.getPreviewUrl(attachmentId)
    }
    
    // 关闭对话框时的清理
    const handleDialogClosed = () => {
      if (currentId.value) {
        loadContractAttachments()
      }
    }
    
    // 关闭上传对话框
    const handleUploadDialogClosed = () => {
      loadContractAttachments()
    }

    // 处理导出Excel
    const handleExportExcel = async () => {
      try {
        const res = await contractAPI.exportExcel()
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = '合同列表.xlsx'
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
        ElMessage.success('导出成功')
      } catch (e) {
        ElMessage.error('导出失败，请稍后重试')
        console.error('导出合同列表失败:', e)
      }
    }

    onMounted(() => {
      getContractList()
    })

    return {
      tableData,
      loading,
      currentPage,
      pageSize,
      total,
      tableHeight,
      searchForm,
      dialogVisible,
      dialogType,
      formRef,
      form,
      rules,
      employeeOptions,
      employeeLoading,
      handleSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      handleTableResize,
      remoteSearchEmployee,
      submitForm,
      formatDate,
      calculateContractYears,
      getContractTypeTag,
      handleView,
      dialogTitle,
      
      // 附件相关
      currentId, 
      contractAttachments,
      attachmentsLoading,
      showUploadDialog,
      loadContractAttachments,
      uploadContractAttachment,
      handleUploadSuccess,
      downloadAttachment,
      deleteAttachment,
      previewAttachment,
      handleDialogClosed,
      handleUploadDialogClosed,
      handleExportExcel,
      Plus, Download, View, Edit, Delete
    }
  }
}
</script>

<style scoped>
.contracts-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-x: auto;
}

.pagination-container {
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
}

/* 合同表单样式 */
.contract-form {
  padding: 0 10px;
}

.form-section {
  margin-bottom: 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.no-attachments-info {
  margin-top: 10px;
}

/* 表格样式 */
:deep(.el-table) {
  margin-bottom: 20px;
  border: none;
}

:deep(.el-table__header) {
  background-color: #F5F7FA;
}

:deep(.el-table th) {
  background-color: #F5F7FA !important;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table .el-table__fixed-right) {
  background-color: #fff;
}

:deep(.el-table .el-table__fixed-right th) {
  background-color: #F5F7FA !important;
}

:deep(.el-table .el-table__fixed-right td) {
  background-color: #fff;
}

/* 对话框样式 */
:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f9f9f9;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f9f9f9;
}

/* 按钮样式优化 */
:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-button--small.is-plain) {
  background-color: #fff;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-button--small.is-plain:hover) {
  background-color: #ecf5ff;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-button--small.is-plain:active) {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .contracts-container {
    padding: 0;
  }

  .search-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  :deep(.el-form--inline .el-form-item) {
    margin-right: 0;
    width: 100%;
  }
}

/* 合同弹窗专属附件列表样式，严格遵循 attachment-list-style.mdc 规范 */
.contract-attachment-card {
  background: #fafbfc;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(0,0,0,0.03);
  border: 1px solid #dcdfe6;
  padding: 18px 18px 10px 18px;
  margin-top: 24px;
}
.contract-attachment-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}
.contract-attachment-card-label {
  color: #409EFF;
  font-size: 15px;
  font-weight: 600;
  line-height: 1.2;
  padding-left: 2px;
}
.contract-attachment-card-content {
  min-height: 80px;
}
.contract-attachment-card .upload-btn {
  margin-left: auto;
}
.contract-attachment-card .attachment-list {
  background: transparent;
  border: none;
  box-shadow: none;
  padding: 0;
}
.contract-attachment-card .el-table {
  min-width: 800px;
}
.contract-attachment-card .el-table__body tr:hover td {
  background: #f0f7ff;
}
.contract-attachment-card .el-table__row .el-table__cell:first-child .cell {
  cursor: pointer;
  color: #409EFF;
  font-weight: 500;
}
.contract-attachment-card .el-table__row .el-table__cell:first-child .cell:hover {
  text-decoration: underline;
}
.contract-attachment-card .el-empty {
  margin: 32px 0;
}
.contract-attachment-card .el-button {
  border-radius: 4px;
  margin-right: 8px;
}
.contract-attachment-card .el-button:last-child {
  margin-right: 0;
}

.header-buttons .el-button span {
    margin-left: 4px;
}

:deep(.action-buttons) {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style> 